import operate from '@dfeidao/atom-nodejs/db/operate';
import query from '@dfeidao/atom-nodejs/db/query';
import log from '@dfeidao/atom-nodejs/logger/log';
import { IncomingHttpHeaders } from 'http';
import { productid, systemid } from '../../atom/config';

interface Message {
	cookie: {
		uk: string;
		[key: string]: string
	};
	urls: {
		base: string;
		origin: string;
		url: string;
	};
	query: {};
	params: {};
	headers: {};
	captcha: string;
	data: {
		equip_no: string;
	};
	design_data: Array<{
		attr_no: string;
		attr_name: string;
		attr_value: string;
	}>;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:e:\考核-2\kh\src\device-management-ygh\zj-000010\s011,action_id:' + action_id);

	const q = query(action_id, session_id, systemid);
	q.prepare('equ_user_defined_attribute', ['_id'], { productid, equip_no: message.data.equip_no }, 200, 1, [], []);
	const [res] = await q.exec<{ _id: string }>();
	const { exec, update, del, insert } = operate(action_id, session_id, systemid);
	res.forEach((v) => {
		del('equ_user_defined_attribute', { _id: v._id });
	});
	if (message.design_data && message.design_data.length > 0) {
		message.design_data.forEach((j) => {
			insert('equ_user_defined_attribute', {
				equip_no: message.data.equip_no,
				attr_no: j.attr_no,
				attr_name: j.attr_name,
				attr_value: j.attr_value,
				productid
			});
		});
	}
	const t = await exec();
	log('Service end path:e:\考核-2\kh\src\device-management-ygh\zj-000010\s011,action_id:' + action_id);
	return {
		data: t
	};
}
